import { ref, watch } from 'vue'
import { getArticles, getArticlesByUser, getFavoritedArticles } from 'src/services/article'

const useArticles = (type: string, username: string = '') => {
  const articles = ref<Article[]>([])
  const articlesCount = ref<number>(0)
  const page = ref<number>(1)

  const fetchArticles = async () => {
    articles.value = []
    let responsePromise: Promise<ArticlesResponse>
    if (type === 'home') {
      responsePromise = getArticles(page.value)
    } else if (type === 'user') {
      responsePromise = getArticlesByUser(username, page.value)
    } else {
      responsePromise = getFavoritedArticles(username, page.value)
    }
    const response = await responsePromise
    articles.value = response.articles
    articlesCount.value = response.articlesCount
  }

  const changePage = (value: number) => {
    page.value = value
  }

  watch(page, async () => {
    await fetchArticles()
  })

  return {
    articles,
    articlesCount,
    page,
    changePage,
    fetchArticles
  }
}

export default useArticles